/* 
 * Project:    SerialPort Terminal
 * Company:    Coad .NET, http://coad.net
 * Author:     Noah Coad, http://coad.net/noah
 * Created:    March 2005
 * 
 * Notes:      This was created to demonstrate how to use the SerialPort control for
 *             communicating with your PC's Serial RS-232 COM Port
 * 
 *             It is for educational purposes only and not sanctified for industrial use. :)
 *             Written to support the blog post article at: http://msmvps.com/blogs/coad/archive/2005/03/23/39466.aspx
 * 
 *             Search for "comport" to see how I'm using the SerialPort control.
 */

#region Namespace Inclusions
using System;
using System.Linq;
using System.Data;
using System.Text;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;

using SerialPortTerminal.Properties;
using System.Threading;
using System.IO;
//for Graph
using System.Collections;
using ZedGraph;
using System.Diagnostics;
using System.Xml;
#endregion

namespace SerialPortTerminal
{
    #region Public Enumerations
    public enum DataMode { Text, Hex }
    public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
    #endregion

    public partial class frmTerminal : Form
    {
        #region Local Variables

        // The main control for communicating through the RS-232 port
        private SerialPort comport = new SerialPort();

        // Various colors for logging info
        private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };

        // Temp holder for whether a key was pressed
        private bool KeyHandled = false;

        private Settings settings = Settings.Default;

        //local variable for graph
        private ZedGraph.ZedGraphControl headsetzg;
        private ZedGraph.ZedGraphControl environmentzg;
        private ZedGraph.ZedGraphControl devicezg;
        private ZedGraph.ZedGraphControl patternzg;
        private BackgroundWorker bw = new BackgroundWorker();
        private ArrayList chkGroups;

        //local variable for sound
        private System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer();
        //local variabel for test functions
        static int n_test=5;
        private bool flag_idv_test=false;
        
        #endregion

        #region Constructor
        public frmTerminal()
        {
            // Load user settings
            settings.Reload();

            //Load xml labels
            XmlTextReader reader = new XmlTextReader("test.xml");
            String testIndex = ""; String testLabel;
            Hashtable htTestLabel = new Hashtable();
            while (reader.Read())
            {
                if (reader.NodeType.Equals(XmlNodeType.Element))
                    testIndex = reader.Name;
                if (reader.NodeType.Equals(XmlNodeType.Text))
                {
                    testLabel = reader.Value;
                    htTestLabel.Add(testIndex, testLabel);
                }
            }

            // Build the form
            InitializeComponent();

            // Restore the users settings
            InitializeControlValues();
            chkGroups = new ArrayList();
            chkGroups.Add(checkBox1);
            chkGroups.Add(checkBox2);
            chkGroups.Add(checkBox3);
            //chkGroups.Add(checkBox4);
            headsetzg = new ZedGraph.ZedGraphControl();
            initGraph(headsetzg, new System.Drawing.Size(340, this.tabControl2.TabPages[0].Height - 10));
            this.tabControl2.TabPages[0].Controls.Add(headsetzg);
            environmentzg = new ZedGraph.ZedGraphControl();
            initGraph(environmentzg, new System.Drawing.Size(pictureBox4.Width - 10, pictureBox4.Height - 10));
            this.pictureBox4.Controls.Add(environmentzg);
            devicezg = new ZedGraph.ZedGraphControl();
            initGraph(devicezg, new System.Drawing.Size(pictureBox5.Width - 10, pictureBox5.Height - 10));
            this.pictureBox5.Controls.Add(devicezg);
            patternzg = new ZedGraph.ZedGraphControl();
            initGraph(patternzg, new System.Drawing.Size(pictureBox6.Width - 10, pictureBox5.Height - 10));
            this.pictureBox6.Controls.Add(patternzg);
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            myPlayer.SoundLocation = @".\test.wav";

            //update UI labels
            lbTitle.Text = (string)htTestLabel["title"];
            label6.Text=(string)htTestLabel["test1"];
            label10.Text = (string)htTestLabel["test2"];
            label11.Text = (string)htTestLabel["test3"];
            label7.Text = (string)htTestLabel["test4"];
            DeviceReport10.Text = (string)htTestLabel["test5"];
            button1.Text = (string)htTestLabel["btnTestAll"];
            button2.Text = (string)htTestLabel["btnStopAll"];
            button3.Text = (string)htTestLabel["btnExit"];
            groupBox1.Text = (string)htTestLabel["report"];
            tabControl2.TabPages[0].Text = (string)htTestLabel["tabPg1"];
            tabControl2.TabPages[1].Text = (string)htTestLabel["tabPg2"];
            checkBox1.Text = (string)htTestLabel["chk1"];
            checkBox2.Text = (string)htTestLabel["chk2"];
            checkBox3.Text = (string)htTestLabel["chk3"];
            // Enable/disable controls based on the current state
            //EnableControls();

            // When data is recieved through the port, call this method
            //comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            //comport.PinChanged += new SerialPinChangedEventHandler(comport_PinChanged);
        }

        void initGraph(ZedGraphControl zg, Size zgSize)
        {

            zg.EditButtons = System.Windows.Forms.MouseButtons.Left;
            zg.EditModifierKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.None)));
            zg.IsAutoScrollRange = false;
            zg.IsEnableHEdit = false;
            zg.IsEnableHPan = true;
            zg.IsEnableHZoom = true;
            zg.IsEnableVEdit = false;
            zg.IsEnableVPan = true;
            zg.IsEnableVZoom = true;
            zg.IsPrintFillPage = true;
            zg.IsPrintKeepAspectRatio = true;
            zg.IsScrollY2 = false;
            zg.IsShowContextMenu = false;
            zg.IsShowCopyMessage = true;
            zg.IsShowCursorValues = false;
            zg.IsShowHScrollBar = false;
            zg.IsShowPointValues = false;
            zg.IsShowVScrollBar = false;
            zg.IsSynchronizeXAxes = false;
            zg.IsSynchronizeYAxes = false;
            zg.IsZoomOnMouseCenter = false;

            zg.LinkButtons = System.Windows.Forms.MouseButtons.Left;
            zg.LinkModifierKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.None)));
            zg.Location = new System.Drawing.Point(0, 12);
            zg.Name = "zg";
            zg.PanButtons = System.Windows.Forms.MouseButtons.Left;
            zg.PanButtons2 = System.Windows.Forms.MouseButtons.Middle;
            zg.PanModifierKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.None)));
            zg.PanModifierKeys2 = System.Windows.Forms.Keys.None;
            zg.PointDateFormat = "g";
            zg.PointValueFormat = "G";
            zg.ScrollMaxX = 0;
            zg.ScrollMaxY = 0;
            zg.ScrollMaxY2 = 0;
            zg.ScrollMinX = 0;
            zg.ScrollMinY = 0;
            zg.ScrollMinY2 = 0;
            zg.Size = zgSize;// new System.Drawing.Size(340, 220);
            zg.TabIndex = 0;
            zg.ZoomButtons = System.Windows.Forms.MouseButtons.Left;
            zg.ZoomButtons2 = System.Windows.Forms.MouseButtons.None;
            zg.ZoomModifierKeys = System.Windows.Forms.Keys.None;
            zg.ZoomModifierKeys2 = System.Windows.Forms.Keys.None;
            zg.ZoomStepFraction = 0.1;
            zg.GraphPane.XAxis.IsVisible = false;
            zg.GraphPane.YAxis.IsVisible = false;
            zg.GraphPane.Title.IsVisible = false;
            //this.headsetzg.Dock = DockStyle.Fill;

        }


        #endregion

        #region Local Methods

        private Thread trdTestHeadset;
        private Thread trdTestInfrared;
        private Thread trdTestLED;
        private Thread trdTestEnv;
        private Thread trdTestFunc;

        /// <summary> Save the user's settings. </summary>
        private void SaveSettings()
        {
            settings.Save();
        }

        /// <summary> Populate the form's controls with default settings. </summary>
        private void InitializeControlValues()
        {
            RefreshComPortList();


            // If it is still avalible, select the last com port used
            if (cmbPortName.Items.Contains(settings.PortName)) cmbPortName.Text = settings.PortName;
            else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = cmbPortName.Items.Count - 1;
            else
            {
                MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        /// <summary> Enable/disable controls based on the app's current state. </summary>
        //private void EnableControls()
        //{
        //Enable/disable controls based on whether the port is open or not
        //gbPortSettings.Enabled = !comport.IsOpen;
        //txtSendData.Enabled = btnSend.Enabled = comport.IsOpen;
        ////chkDTR.Enabled = chkRTS.Enabled = comport.IsOpen;

        //if (comport.IsOpen) btnOpenPort.Text = "&Close Port";
        //else btnOpenPort.Text = "&Open Port";
        //}


        /// <summary> Log data to the terminal window. </summary>
        /// <param name="msgtype"> The type of message to be written. </param>
        /// <param name="msg"> The string containing the message to be shown. </param>
        private void Log(LogMsgType msgtype, string msg)
        {
            rtfTerminal.Invoke(new EventHandler(delegate
            {
                rtfTerminal.SelectedText = string.Empty;
                rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
                rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
                rtfTerminal.AppendText(msg);
                rtfTerminal.ScrollToCaret();
            }));
        }

        /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
        /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
        /// <returns> Returns an array of bytes. </returns>
        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
        /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
        /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            return sb.ToString().ToUpper();
        }
        #endregion



        #region Event Handlers
        private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            // Show the user the about dialog
            (new frmAbout()).ShowDialog(this);
        }

        private void frmTerminal_Shown(object sender, EventArgs e)
        {
            Log(LogMsgType.Normal, String.Format("Application Started at {0}\n", DateTime.Now));
        }
        private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e)
        {
            // The form is closing, save the user's preferences
            SaveSettings();
        }


        private void OpenPort()
        {
            bool error = false;


            // Set the port's settings
            //comport.BaudRate = int.Parse(cmbBaudRate.Text);
            //comport.DataBits = int.Parse(cmbDataBits.Text);
            //comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
            //comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
            string[] ports = SerialPort.GetPortNames();
            ports = OrderedPortNames();
            comport.PortName = ports.LastOrDefault();

            try
            {
                // Open the port
                comport.Open();
            }
            catch (UnauthorizedAccessException) { error = true; }
            catch (IOException) { error = true; }
            catch (ArgumentException) { error = true; }

            if (error) MessageBox.Show(this, "Could not open the COM port.  Most likely it is already in use, has been removed, or is unavailable.", "COM Port Unavalible", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            else
            {

            }
        }


        /*private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
                // If the com port has been closed, do nothing
                if (!comport.IsOpen) return;

          // This method will be called when there is data waiting in the port's buffer

          // Determain which mode (string or binary) the user is in
          if (CurrentDataMode == DataMode.Text)
          {
            // Read all the data waiting in the buffer
            string data = comport.ReadExisting();

            // Display the text to the user in the terminal
            //Log(LogMsgType.Incoming, data);
          }
          else
          {
            // Obtain the number of bytes waiting in the port's buffer
            int bytes = comport.BytesToRead;

            // Create a byte array buffer to hold the incoming data
            byte[] buffer = new byte[bytes];

            // Read the data from the port and store it in our buffer
            comport.Read(buffer, 0, bytes);

            // Show the user the incoming data in hex format
            Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
          }
        }*/

        #endregion


        private void tmrCheckComPorts_Tick(object sender, EventArgs e)
        {
            // checks to see if COM ports have been added or removed
            // since it is quite common now with USB-to-Serial adapters
            //RefreshComPortList();
        }

        private void RefreshComPortList()
        {
            // Determain if the list of com port names has changed since last checked
            string selected = RefreshComPortList(cmbPortName.Items.Cast<string>(), cmbPortName.SelectedItem as string, comport.IsOpen);

            // If there was an update, then update the control showing the user the list of port names
            if (!String.IsNullOrEmpty(selected))
            {
                cmbPortName.Items.Clear();
                cmbPortName.Items.AddRange(OrderedPortNames());
                cmbPortName.SelectedItem = selected;
            }
        }

        private string[] OrderedPortNames()
        {
            // Just a placeholder for a successful parsing of a string to an integer
            int num;

            // Order the serial port names in numberic order (if possible)
            return SerialPort.GetPortNames().OrderBy(a => a.Length > 3 && int.TryParse(a.Substring(3), out num) ? num : 0).ToArray();
        }

        private string RefreshComPortList(IEnumerable<string> PreviousPortNames, string CurrentSelection, bool PortOpen)
        {
            // Create a new return report to populate
            string selected = null;

            // Retrieve the list of ports currently mounted by the operating system (sorted by name)
            string[] ports = SerialPort.GetPortNames();

            // First determain if there was a change (any additions or removals)
            bool updated = PreviousPortNames.Except(ports).Count() > 0 || ports.Except(PreviousPortNames).Count() > 0;

            // If there was a change, then select an appropriate default port
            if (updated)
            {
                // Use the correctly ordered set of port names
                ports = OrderedPortNames();

                // Find newest port if one or more were added
                string newest = SerialPort.GetPortNames().Except(PreviousPortNames).OrderBy(a => a).LastOrDefault();

                // If the port was already open... (see logic notes and reasoning in Notes.txt)
                if (PortOpen)
                {
                    if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
                    else if (!String.IsNullOrEmpty(newest)) selected = newest;
                    else selected = ports.LastOrDefault();
                }
                else
                {
                    if (!String.IsNullOrEmpty(newest)) selected = newest;
                    else if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
                    else selected = ports.LastOrDefault();
                }
            }

            // If there was a change to the port list, return the recommended default selection
            return selected;
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void rtfTerminal_TextChanged(object sender, EventArgs e)
        {

        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            lbTotalDuration.Text = trackBar1.Value.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            flag_idv_test = false;
            txSensorResult.Text = ""; 
            txInfraredResult.Text = "";
            txLEDResult.Text = "";
            txEnvResult.Text = "";
            txFuncResult.Text = "";
            thread_works();
            disable_excl_btns();


            //trdTestInfrared.Join(); 
            //MessageBox.Show("infared test");
            //MessageBox.Show("led test");
        }
        private void thread_works()
        {
            trdTestHeadset = new Thread(new ThreadStart(this.test_headset));
            trdTestHeadset.IsBackground = true;
            trdTestHeadset.Start();
            // Read all the data waiting in the buffer
            trdTestInfrared = new Thread(new ThreadStart(this.test_infrared));
            trdTestInfrared.IsBackground = true;
            trdTestInfrared.Start();
            trdTestLED = new Thread(new ThreadStart(this.test_led));
            trdTestLED.IsBackground = true;
            trdTestLED.Start();
            trdTestEnv = new Thread(new ThreadStart(this.test_env));
            trdTestEnv.IsBackground = true;
            trdTestEnv.Start(); 
            trdTestFunc = new Thread(new ThreadStart(this.test_func));
            trdTestFunc.IsBackground = true;
            trdTestFunc.Start();
        }

        private void terminate_all_test()
        {
            // If the port is open, close it.
            if (trdTestInfrared!=null&&trdTestInfrared.IsAlive)
                trdTestInfrared.Abort();
            if (trdTestLED!=null&&trdTestLED.IsAlive)
                trdTestLED.Abort();
            if (trdTestEnv != null && trdTestEnv.IsAlive)
                trdTestEnv.Abort();
            if (trdTestFunc != null && trdTestFunc.IsAlive)
                trdTestFunc.Abort();
            //if (trdTestInfrared.IsAlive) trdTestInfrared.Abort();
            if (comport.IsOpen)
                comport.Close();
            //stop the background work
            if (bw.IsBusy == true)
                bw.CancelAsync();
            myPlayer.Stop();
            enable_excl_btns();
        }

        private void enable_excl_btns()
        {
            button1.Enabled = true;
            button4.Enabled = true;
            button5.Enabled = true;
            button6.Enabled = true;
        }

        private void disable_excl_btns()
        {
            button1.Enabled = false;
            button4.Enabled = false;
            button5.Enabled = false;
            button6.Enabled = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // If the port is open, close it.
            if (trdTestHeadset!=null && trdTestHeadset.IsAlive)
            {
                trdTestHeadset.Abort();
                txSensorResult.ForeColor = Color.Red;
                txSensorResult.Text = "Test Terminated";
            }
            if (trdTestInfrared != null && trdTestInfrared.IsAlive)
            {
                trdTestInfrared.Abort();
                txInfraredResult.ForeColor = Color.Red;
                txInfraredResult.Text = "Test Terminated";
            }
            if (trdTestLED != null && trdTestLED.IsAlive)
            {
                trdTestLED.Abort();
                txLEDResult.ForeColor = Color.Red;
                txLEDResult.Text = "Test Terminated";
            }
            if (trdTestEnv != null && trdTestEnv.IsAlive)
            {
                trdTestEnv.Abort();
                txEnvResult.ForeColor = Color.Red;
                txEnvResult.Text = "Test Terminated";
            }
            if (trdTestFunc != null && trdTestFunc.IsAlive)
            {
                trdTestFunc.Abort();
                txFuncResult.ForeColor = Color.Red;
                txFuncResult.Text = "Test Terminated";
            }
            //if (trdTestInfrared.IsAlive) trdTestInfrared.Abort();
            if (comport.IsOpen)
                comport.Close();
            //stop the background work
            if (bw.IsBusy == true)
                bw.CancelAsync();
            myPlayer.Stop();
            enable_excl_btns();
            picPass.Load("fail.bmp");
        }

        private void test_func()
        {
            while (trdTestEnv.IsAlive)
            {
                Thread.Sleep(1000);
            }
            if (comport.IsOpen == false) OpenPort();
            System.DateTime currTime = new System.DateTime();
            currTime = System.DateTime.Now;
            double test_duration = Convert.ToDouble(lbTotalDuration.Text)/n_test;
            System.DateTime endTime = currTime.AddMinutes(test_duration);

            while (System.DateTime.Compare(currTime, endTime) < 0)
            {
                comport.Write("11");
                rtfLEDResult.Invoke(new EventHandler(delegate
                {
                    myPlayer.Play();
                }));
                System.Threading.Thread.Sleep(3000);
                currTime = System.DateTime.Now;
            }
            comport.Close();
            myPlayer.Stop();
            txFuncResult.ForeColor = System.Drawing.Color.Green;
            txFuncResult.Text = "... Test OK";
            picPass.Load("pass.bmp");
            if (bw.IsBusy == true)
                bw.CancelAsync();
        }

        private void test_env()
        {
            while (trdTestLED.IsAlive)
            {
                Thread.Sleep(1000);
            }
            if (comport.IsOpen == false) OpenPort();
            System.DateTime currTime = new System.DateTime();
            currTime = System.DateTime.Now;
            double test_duration = Convert.ToDouble(lbTotalDuration.Text) / n_test;
            System.DateTime endTime = currTime.AddMinutes(test_duration);

            while (System.DateTime.Compare(currTime, endTime) < 0)
            {
                comport.Write("11");
                rtfLEDResult.Invoke(new EventHandler(delegate
                {
                    myPlayer.Play();
                }));
                System.Threading.Thread.Sleep(3000);
                currTime = System.DateTime.Now;
            }
            comport.Close();
            myPlayer.Stop();
            txEnvResult.ForeColor = System.Drawing.Color.Green;
            txEnvResult.Text = "... Test OK";
        }

        private void test_led()
        {
            if (trdTestInfrared == null)
            { }  //indivisual test, do not check previous thread.
            else //run all test, check previous tests
            {
                while (trdTestInfrared.IsAlive)
                {
                    Thread.Sleep(1000);
                }
            }
            if (comport.IsOpen == false) OpenPort();
            System.DateTime currTime = new System.DateTime();
            currTime = System.DateTime.Now;
            double test_duration = Convert.ToDouble(lbTotalDuration.Text) / n_test;
            System.DateTime endTime = currTime.AddMinutes(test_duration);

            int error_count = 0;
            while (System.DateTime.Compare(currTime, endTime) < 0)
            {
                //com port setting is done when comport class is initialized
                if (comport.IsOpen == false) OpenPort();
                string data = comport.ReadExisting();
                data = string.Concat(data, comport.ReadExisting());
                data = string.Concat(data, comport.ReadExisting());
                comport.Write("11");
                comport.Close();
                currTime = System.DateTime.Now;
                rtfLEDResult.Invoke(new EventHandler(delegate
                {
                    rtfLEDResult.SelectedText = string.Empty;
                    //if (data.Length > 0)
                    if (true)
                    {
                        error_count = 0;
                        rtfLEDResult.ForeColor = Color.LimeGreen;
                        rtfLEDResult.AppendText("Signal Detected ... OK\n");
                        myPlayer.Play();
                        if (bw.IsBusy != true)
                        {
                            bw.RunWorkerAsync();
                        }
                    }
                    else
                    {
                        error_count = error_count + 1;
                        rtfLEDResult.ForeColor = Color.Red;
                        rtfLEDResult.AppendText("Failed !\n");
                    }

                    rtfLEDResult.ScrollToCaret();
                    //this.tabControl2.TabPages[0].Controls.Remove(headsetzg);
                }));
                currTime = System.DateTime.Now;
                if (error_count >= 3)
                {
                    if (comport.IsOpen) comport.Close();
                    txLEDResult.ForeColor = System.Drawing.Color.Red;
                    txLEDResult.Text = "Test Failed !";
                    if (!flag_idv_test)
                    {
                        txEnvResult.ForeColor = System.Drawing.Color.Red;
                        txEnvResult.Text = "Test Terminated !";
                        txFuncResult.ForeColor = System.Drawing.Color.Red;
                        txFuncResult.Text = "Test Terminated!";
                        lbErrorMsgInfrared.ForeColor = System.Drawing.Color.Red;
                        lbErrorMsgInfrared.Text = "Error code oxEEF049";
                        picPass.Load("fail.bmp");
                        terminate_all_test();
                    }
                    if (flag_idv_test) enable_excl_btns();
                    break;
                }
                System.Threading.Thread.Sleep(2000);
            }
            if (comport.IsOpen) comport.Close();
            myPlayer.Stop();
            if (error_count < 3)
            {
                lbErrorMsgLED.ForeColor = System.Drawing.Color.LimeGreen;
                lbErrorMsgLED.Text = "No Error Code...";
                txLEDResult.ForeColor = System.Drawing.Color.Green;
                txLEDResult.Text = "... Test OK";
            }
            if (flag_idv_test) enable_excl_btns();
        }

        private void test_infrared()
        {
            if (trdTestHeadset == null)
            { }  //do not check previous thread in individual test
            else
            {
                //threading process for run all tests
                while (trdTestHeadset.IsAlive)
                {
                    Thread.Sleep(1000);
                }
            }
            if (comport.IsOpen == false) OpenPort();
            System.DateTime currTime = new System.DateTime();
            currTime = System.DateTime.Now;
            double test_duration = Convert.ToDouble(lbTotalDuration.Text) / n_test;
            System.DateTime endTime = currTime.AddMinutes(test_duration);

            int error_count = 0;
            while (System.DateTime.Compare(currTime, endTime) < 0)
            {
                //com port setting is done when comport class is initialized
                if (comport.IsOpen == false) OpenPort();
                string data = comport.ReadExisting();
                data = string.Concat(data, comport.ReadExisting());
                data = string.Concat(data, comport.ReadExisting());
                comport.Write("11");
                comport.Close();
                currTime = System.DateTime.Now;
                rtfHeadsetResult.Invoke(new EventHandler(delegate
                {
                    rtfInfraredResult.SelectedText = string.Empty;
                    //if (data.Length > 0)
                    if (true)
                    {
                        error_count = 0;
                        rtfInfraredResult.ForeColor = Color.LimeGreen;
                        rtfInfraredResult.AppendText("Signal Detected ... OK\n");
                        myPlayer.Play();
                        if (bw.IsBusy != true)
                        {
                            bw.RunWorkerAsync();
                        }
                    }
                    else
                    {
                        error_count = error_count + 1;
                        rtfInfraredResult.ForeColor = Color.Red;
                        rtfInfraredResult.AppendText("Failed !\n");
                    }

                    rtfInfraredResult.ScrollToCaret();
                    //this.tabControl2.TabPages[0].Controls.Remove(headsetzg);
                }));
                currTime = System.DateTime.Now;
                if (error_count >= 3)
                {
                    if (comport.IsOpen) comport.Close();
                    txInfraredResult.ForeColor = System.Drawing.Color.Red;
                    txInfraredResult.Text = "Test Failed !";
                    if (!flag_idv_test)
                    {
                        txLEDResult.ForeColor = System.Drawing.Color.Red;
                        txLEDResult.Text = "Test Terminated !";
                        txEnvResult.ForeColor = System.Drawing.Color.Red;
                        txEnvResult.Text = "Test Terminated !";
                        txFuncResult.ForeColor = System.Drawing.Color.Red;
                        txFuncResult.Text = "Test Terminated!";
                        lbErrorMsgInfrared.ForeColor = System.Drawing.Color.Red;
                        lbErrorMsgInfrared.Text = "Error code oxEEF032";
                        picPass.Load("fail.bmp");
                        terminate_all_test();
                    }
                    if (flag_idv_test) enable_excl_btns();
                    break;
                }
                System.Threading.Thread.Sleep(2000);
            }
            if (comport.IsOpen) comport.Close();
            myPlayer.Stop();
            if (error_count < 3)
            {
                lbErrorMsgInfrared.ForeColor = System.Drawing.Color.LimeGreen;
                lbErrorMsgInfrared.Text = "No Error Code...";
                txInfraredResult.ForeColor = System.Drawing.Color.Green;
                txInfraredResult.Text = "... Test OK";
            }
            if (flag_idv_test) enable_excl_btns();
        }
        private void test_headset()
        {
            System.DateTime currTime = new System.DateTime();
            currTime = System.DateTime.Now;
            double test_duration = Convert.ToDouble(lbTotalDuration.Text) / n_test;
            System.DateTime endTime = currTime.AddMinutes(test_duration);
            int error_count = 0;
            while (System.DateTime.Compare(currTime, endTime) < 0)
            {
                //com port setting is done when comport class is initialized
                OpenPort();
                string data = comport.ReadExisting();
                data = string.Concat(data, comport.ReadExisting());
                data = string.Concat(data, comport.ReadExisting());
                comport.Write("11");
                comport.Close();
                currTime = System.DateTime.Now;
                rtfHeadsetResult.Invoke(new EventHandler(delegate
                {
                    rtfHeadsetResult.SelectedText = string.Empty;
                    //if (data.Length > 0)
                    if (true)
                    {
                        error_count = 0;
                        rtfHeadsetResult.ForeColor = Color.LimeGreen;
                        rtfHeadsetResult.AppendText("Signal Detected ... OK\n");
                        myPlayer.Play();
                        if (bw.IsBusy != true)
                        {
                            bw.RunWorkerAsync();
                        }
                    }
                    else
                    {
                        error_count = error_count + 1;
                        rtfHeadsetResult.ForeColor = Color.Red;
                        rtfHeadsetResult.AppendText("Failed !\n");
                    }

                    rtfHeadsetResult.ScrollToCaret();
                    //this.tabControl2.TabPages[0].Controls.Remove(headsetzg);
                }));
                currTime = System.DateTime.Now;
                if (error_count >= 3)
                {
                    if (comport.IsOpen) comport.Close();
                    txSensorResult.ForeColor = System.Drawing.Color.Red;
                    txSensorResult.Text = "Test Failed !";
                    txInfraredResult.ForeColor = System.Drawing.Color.Red;
                    txInfraredResult.Text = "Test Terminated !";
                    txLEDResult.ForeColor = System.Drawing.Color.Red;
                    txLEDResult.Text = "Test Terminated !";
                    txEnvResult.ForeColor = System.Drawing.Color.Red;
                    txEnvResult.Text = "Test Terminated !";
                    txFuncResult.ForeColor = System.Drawing.Color.Red;
                    txFuncResult.Text = "Test Terminated!";
                    lbErrorMsgSensor.ForeColor = System.Drawing.Color.Red;
                    lbErrorMsgSensor.Text = "Error code oxEEF028";
                    picPass.Load("fail.bmp");
                    terminate_all_test();
                    if (flag_idv_test) enable_excl_btns();
                    break;
                }
                System.Threading.Thread.Sleep(2000);
            }
            if (comport.IsOpen) comport.Close();
            myPlayer.Stop();
            if (error_count < 3)
            {
                lbErrorMsgSensor.ForeColor = System.Drawing.Color.LimeGreen;
                lbErrorMsgSensor.Text = "No Error Code...";
                txSensorResult.ForeColor = System.Drawing.Color.Green;
                txSensorResult.Text = "... Test OK";
            }
            if (flag_idv_test) enable_excl_btns();
        }

        private void CreateR4Graph(ZedGraphControl zgc, Color linecolor, int linecount, ArrayList chkboxs, Color backgroundcolor, Color gridcolor)
        {
            //int linecount = 2;
            GraphPane myPane = zgc.GraphPane;

            //myPane.Chart.Border.Color = Color.FromArgb(255, 178, 214, 217);
            //myPane.Border.Color = Color.FromArgb(0, 255, 255, 255);

            // Set the titles and axis labels
            myPane.Title.Text = "";
            myPane.XAxis.Title.Text = "";
            myPane.XAxis.IsVisible = true;
            myPane.XAxis.Scale.IsVisible = false;
            myPane.YAxis.Title.Text = "";
            myPane.YAxis.IsVisible = true;
            myPane.XAxis.Type = AxisType.Date;
            myPane.X2Axis.Type = AxisType.Date;
            myPane.XAxis.CrossAuto = true;

            myPane.XAxis.MajorGrid.IsVisible = true;
            myPane.XAxis.MajorGrid.Color = gridcolor;
            myPane.XAxis.MajorGrid.DashOff = 1;
            myPane.XAxis.MajorGrid.DashOn = 5;
            myPane.XAxis.MajorGrid.PenWidth = 1;

            myPane.XAxis.MinorGrid.IsVisible = true;
            myPane.XAxis.MinorGrid.Color = gridcolor;
            myPane.XAxis.MinorGrid.DashOff = 1;
            myPane.XAxis.MinorGrid.DashOn = 5;
            myPane.XAxis.MinorGrid.PenWidth = 1;

            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.MajorGrid.Color = gridcolor;
            myPane.YAxis.MajorGrid.DashOff = 1;
            myPane.YAxis.MajorGrid.DashOn = 5;
            myPane.YAxis.MajorGrid.PenWidth = 1;

            myPane.YAxis.MinorGrid.IsVisible = true;
            myPane.YAxis.MinorGrid.Color = gridcolor;
            myPane.YAxis.MinorGrid.DashOff = 1;
            myPane.YAxis.MinorGrid.DashOn = 5;
            myPane.YAxis.MinorGrid.PenWidth = 1;

            //to control the step unit
            myPane.YAxis.Scale.MajorStep = 2;
            //myPane.Chart.Fill.IsVisible = false;
            myPane.XAxis.Scale.Max = 59;
            zgc.GraphPane.CurveList.Clear();
            // Make up some data points from the Sine function
            for (int i = 0; i < linecount; i++)
            {
                PointPairList list = new PointPairList();
                Random innerRnd = new Random();
                double tmp; tmp = 0;
                double y; y = 0;
                for (double x = 0; x < 60; x++)
                {
                    //this is the generated graph function
                    switch (i)
                    {
                        case 0:
                            tmp = (innerRnd.Next() % 10.0) - 5.0;
                            y = Math.Sin(x * tmp * Math.PI / 15.0);
                            break;
                        case 1:
                            tmp = (innerRnd.Next() % 20.0) - 10.0;
                            y = (3 / (1 + Math.Exp((-x + 30) / 10)) - 1.5) + (tmp / (20 + 3 * Math.Abs(x - 30)));
                            break;
                        case 2:
                            tmp = (innerRnd.Next() % 20.0) - 10.0;
                            y = Math.Sin(x * Math.PI / 30.0) * (1 + tmp / 20);
                            break;
                        default:
                            tmp = (innerRnd.Next() % 20.0) - 10.0;
                            y = Math.Sin(x * tmp * Math.PI / 15.0);
                            break;
                    }
                    //Trace.WriteLine(tmp.ToString());
                    list.Add(x, y);
                }

                // Generate a blue curve with circle symbols, and "My Curve 2" in the legend
                LineItem myCurve = myPane.AddCurve("", list, (linecolor == Color.Empty) ? LogMsgTypeColor[(int)chkboxs[i]] : linecolor,
                    (linecolor == Color.Empty) ? SymbolType.Circle : SymbolType.None);
                myCurve.Line.IsSmooth = true;
                // Fill the area under the curve with a white-red gradient at 45 degrees
                //myCurve.Line.Fill = new Fill(Color.White, Color.Red, 45F);
                // Make the symbols opaque by filling them with white
                myCurve.Symbol.Fill = new Fill((linecolor == Color.Empty) ? LogMsgTypeColor[(int)chkboxs[i]] : linecolor);

                // Fill the axis background with a color gradient
                myPane.Chart.Fill = new Fill(backgroundcolor, backgroundcolor, 45F);

                // Fill the pane background with a color gradient
                myPane.Fill = new Fill(Color.LightGray, Color.LightGray, 45F);

                // Calculate the Axis Scale Ranges

            }
            zgc.AxisChange();
            //zgc.Invalidate();
        }


        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            while (true)
            {
                //if the cancell is set, break the loop
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    Thread.Sleep(200);
                    int linecount = 0;
                    ArrayList chk = new ArrayList();
                    for (int i = 0; i < chkGroups.Count; i++)
                    {
                        if (((CheckBox)chkGroups[i]).Checked)
                        {
                            linecount++;
                            chk.Add(i);
                        }
                    }
                    CreateR4Graph(headsetzg, Color.Empty, linecount, chk, Color.White, Color.LightYellow);
                    headsetzg.Invalidate();

                    if (trdTestEnv!=null&& trdTestLED.IsAlive == false)
                    {
                        CreateR1Graph(environmentzg, Color.Empty, 2, Color.Black, Color.Black);
                        environmentzg.Invalidate();
                    }
                    CreateR2Graph(devicezg, Color.Green, 1, chk, Color.Black, Color.Black);
                    devicezg.Invalidate();
                    if (trdTestFunc!=null&&trdTestEnv.IsAlive == false)
                    {
                        CreateR3Graph(patternzg, Color.Empty, 2, Color.Black, Color.Black);
                        patternzg.Invalidate();
                    }

                    //worker.ReportProgress((i * 10));
                }
            }
        }

        private void CreateR1Graph(ZedGraphControl zgc, Color linecolor, int linecount, Color backgroundcolor, Color gridcolor)
        {
            //int linecount = 2;
            GraphPane myPane = zgc.GraphPane;

            //myPane.Chart.Border.Color = Color.FromArgb(255, 178, 214, 217);
            //myPane.Border.Color = Color.FromArgb(0, 255, 255, 255);

            // Set the titles and axis labels
            myPane.Title.Text = "";
            myPane.XAxis.Title.Text = "";
            myPane.XAxis.IsVisible = true;
            myPane.XAxis.Scale.IsVisible = false;
            myPane.YAxis.Title.Text = "";
            myPane.YAxis.IsVisible = true;
            myPane.XAxis.Type = AxisType.Date;
            myPane.X2Axis.Type = AxisType.Date;
            myPane.XAxis.CrossAuto = true;

            myPane.XAxis.MajorGrid.IsVisible = true;
            myPane.XAxis.MajorGrid.Color = gridcolor;
            myPane.XAxis.MajorGrid.DashOff = 1;
            myPane.XAxis.MajorGrid.DashOn = 5;
            myPane.XAxis.MajorGrid.PenWidth = 1;

            myPane.XAxis.MinorGrid.IsVisible = true;
            myPane.XAxis.MinorGrid.Color = gridcolor;
            myPane.XAxis.MinorGrid.DashOff = 1;
            myPane.XAxis.MinorGrid.DashOn = 5;
            myPane.XAxis.MinorGrid.PenWidth = 1;

            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.MajorGrid.Color = gridcolor;
            myPane.YAxis.MajorGrid.DashOff = 1;
            myPane.YAxis.MajorGrid.DashOn = 5;
            myPane.YAxis.MajorGrid.PenWidth = 1;

            myPane.YAxis.MinorGrid.IsVisible = true;
            myPane.YAxis.MinorGrid.Color = gridcolor;
            myPane.YAxis.MinorGrid.DashOff = 1;
            myPane.YAxis.MinorGrid.DashOn = 5;
            myPane.YAxis.MinorGrid.PenWidth = 1;

            //to control the step unit
            myPane.YAxis.Scale.MajorStep = 2;
            myPane.YAxis.Scale.Max = 100;
            myPane.YAxis.Scale.Min = -100;
            //myPane.Chart.Fill.IsVisible = false;
            myPane.XAxis.Scale.Max = 59;
            zgc.GraphPane.CurveList.Clear();
            // Make up some data points from the Sine function
            for (int i = 0; i < linecount; i++)
            {
                PointPairList list = new PointPairList();
                Random innerRnd = new Random();
                double baseline;
                double amp = 0.0;
                double tmp = 0.0;
                double spike_overcharge_pos = 15 + innerRnd.Next() % 30;

                for (double x = 0; x < 60; x++)
                {
                    //this is the generated graph function
                    double y;
                    y = 0;
                    switch (i)
                    {
                        case 0:
                            tmp = Math.Pow((innerRnd.Next() % 6.0) - 3.0, 2);
                            baseline = 10;
                            spike_overcharge_pos = spike_overcharge_pos + (innerRnd.Next() % 20 - 10);
                            if (x % 2 == 0)
                            {
                                if ((int)x == spike_overcharge_pos || (int)x == spike_overcharge_pos + 1)
                                    amp = 60+innerRnd.Next()%20;
                                else
                                    amp = 0;
                                y = baseline+(amp + tmp) * Math.Pow(-1, x);
                            }
                            else
                            {
                                y = baseline + Math.Abs(amp - tmp) * Math.Pow(-1, x);
                            }
                            break;
                        case 1:
                            tmp = Math.Pow((innerRnd.Next() % 6.0) - 3.0, 2);
                            baseline = -20;
                            if (x % 2 == 0)
                            {
                                if ((int)x == spike_overcharge_pos || (int)x == spike_overcharge_pos + 1)
                                    amp = 80 + innerRnd.Next()%20;
                                else
                                    amp = 0;
                                y = baseline + (amp + tmp) * Math.Pow(-1, x);
                            }
                            else
                            {
                                y = baseline + Math.Abs(amp - tmp) * Math.Pow(-1, x);
                            }
                            break;
                        default:
                            tmp = (innerRnd.Next() % 20.0) - 10.0;
                            y = Math.Sin(x * tmp * Math.PI / 15.0);
                            break;
                    }
                    list.Add(x, y);
                }

                // Generate a blue curve with circle symbols, and "My Curve 2" in the legend
                if (i == 0)
                    linecolor = Color.LightYellow;
                else
                    linecolor = Color.LightSkyBlue;
                LineItem myCurve = myPane.AddCurve("", list, linecolor,
                    SymbolType.None);
                myCurve.Line.IsSmooth = true;
                // Fill the area under the curve with a white-red gradient at 45 degrees
                //myCurve.Line.Fill = new Fill(Color.White, Color.Red, 45F);
                // Make the symbols opaque by filling them with white
                myCurve.Symbol.Fill = new Fill((linecolor == Color.Empty) ? LogMsgTypeColor[i] : linecolor);

                // Fill the axis background with a color gradient
                //myPane.Chart.Fill = new Fill(backgroundcolor, backgroundcolor, 45F);

                // Fill the pane background with a color gradient
                myPane.Fill = new Fill(Color.LightGray, Color.LightGray, 45F);
            }
            // Calculate the Axis Scale Ranges
            //zgc.Invalidate();
        }

        private void CreateR2Graph(ZedGraphControl zgc, Color linecolor, int linecount, ArrayList chkboxs, Color backgroundcolor, Color gridcolor)
        {
            //int linecount = 2;
            GraphPane myPane = zgc.GraphPane;

            //myPane.Chart.Border.Color = Color.FromArgb(255, 178, 214, 217);
            //myPane.Border.Color = Color.FromArgb(0, 255, 255, 255);

            // Set the titles and axis labels
            myPane.Title.Text = "";
            myPane.XAxis.Title.Text = "";
            myPane.XAxis.IsVisible = true;
            myPane.XAxis.Scale.IsVisible = false;
            myPane.YAxis.Title.Text = "";
            myPane.YAxis.IsVisible = true;
            myPane.XAxis.Type = AxisType.Date;
            myPane.X2Axis.Type = AxisType.Date;
            myPane.XAxis.CrossAuto = true;

            myPane.XAxis.MajorGrid.IsVisible = true;
            myPane.XAxis.MajorGrid.Color = gridcolor;
            myPane.XAxis.MajorGrid.DashOff = 1;
            myPane.XAxis.MajorGrid.DashOn = 5;
            myPane.XAxis.MajorGrid.PenWidth = 1;

            myPane.XAxis.MinorGrid.IsVisible = true;
            myPane.XAxis.MinorGrid.Color = gridcolor;
            myPane.XAxis.MinorGrid.DashOff = 1;
            myPane.XAxis.MinorGrid.DashOn = 5;
            myPane.XAxis.MinorGrid.PenWidth = 1;

            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.MajorGrid.Color = gridcolor;
            myPane.YAxis.MajorGrid.DashOff = 1;
            myPane.YAxis.MajorGrid.DashOn = 5;
            myPane.YAxis.MajorGrid.PenWidth = 1;

            myPane.YAxis.MinorGrid.IsVisible = true;
            myPane.YAxis.MinorGrid.Color = gridcolor;
            myPane.YAxis.MinorGrid.DashOff = 1;
            myPane.YAxis.MinorGrid.DashOn = 5;
            myPane.YAxis.MinorGrid.PenWidth = 1;

            //to control the step unit
            myPane.YAxis.Scale.MajorStep = 2;
            //myPane.Chart.Fill.IsVisible = false;
            myPane.XAxis.Scale.Max = 199;
            zgc.GraphPane.CurveList.Clear();
            // Make up some data points from the Sine function

            PointPairList list = new PointPairList();
            Random innerRnd = new Random();
            double amp = 0.0;
            double tmp = 0.0;
            double spike_overcharge_pos = 50 + innerRnd.Next() % 100;

            for (double x = 0; x < 199; x++)
            {
                //this is the generated graph function
                double y;
                y = 0;
                tmp = Math.Pow((innerRnd.Next() % 10.0) - 5.0, 2);
                if (x % 2 == 1)
                {
                    amp = 100 * Math.Exp(-Math.Abs(spike_overcharge_pos - x) / 5) + tmp;
                    //tmp = Math.Pow((innerRnd.Next() % 10.0) - 5.0, 2);
                    y = amp * Math.Pow(-1, x);
                }
                else
                {
                    y = amp * Math.Pow(-1, x);
                }
                list.Add(x, y);
            }

            // Generate a blue curve with circle symbols, and "My Curve 2" in the legend
            LineItem myCurve = myPane.AddCurve("", list, (linecolor == Color.Empty) ? LogMsgTypeColor[(int)chkboxs[1]] : linecolor,
                SymbolType.None);
            myCurve.Line.IsSmooth = true;
            // Fill the area under the curve with a white-red gradient at 45 degrees
            //myCurve.Line.Fill = new Fill(Color.White, Color.Red, 45F);
            // Make the symbols opaque by filling them with white
            myCurve.Symbol.Fill = new Fill((linecolor == Color.Empty) ? LogMsgTypeColor[1] : linecolor);

            // Fill the axis background with a color gradient
            myPane.Chart.Fill = new Fill(backgroundcolor, backgroundcolor, 45F);

            // Fill the pane background with a color gradient
            myPane.Fill = new Fill(Color.LightGray, Color.LightGray, 45F);

            // Calculate the Axis Scale Ranges

            zgc.AxisChange();
            //zgc.Invalidate();
        }

        private void CreateR3Graph(ZedGraphControl zgc, Color linecolor, int linecount, Color backgroundcolor, Color gridcolor)
        {
            //int linecount = 2;
            GraphPane myPane = zgc.GraphPane;

            //myPane.Chart.Border.Color = Color.FromArgb(255, 178, 214, 217);
            //myPane.Border.Color = Color.FromArgb(0, 255, 255, 255);

            // Set the titles and axis labels
            myPane.Title.Text = "";
            myPane.XAxis.Title.Text = "";
            myPane.XAxis.IsVisible = true;
            myPane.XAxis.Scale.IsVisible = false;
            myPane.YAxis.Title.Text = "";
            myPane.YAxis.IsVisible = true;
            myPane.XAxis.Type = AxisType.Date;
            myPane.X2Axis.Type = AxisType.Date;
            myPane.XAxis.CrossAuto = true;

            myPane.XAxis.MajorGrid.IsVisible = true;
            myPane.XAxis.MajorGrid.Color = gridcolor;
            myPane.XAxis.MajorGrid.DashOff = 1;
            myPane.XAxis.MajorGrid.DashOn = 5;
            myPane.XAxis.MajorGrid.PenWidth = 1;

            myPane.XAxis.MinorGrid.IsVisible = true;
            myPane.XAxis.MinorGrid.Color = gridcolor;
            myPane.XAxis.MinorGrid.DashOff = 1;
            myPane.XAxis.MinorGrid.DashOn = 5;
            myPane.XAxis.MinorGrid.PenWidth = 1;

            myPane.YAxis.MajorGrid.IsVisible = true;
            myPane.YAxis.MajorGrid.Color = gridcolor;
            myPane.YAxis.MajorGrid.DashOff = 1;
            myPane.YAxis.MajorGrid.DashOn = 5;
            myPane.YAxis.MajorGrid.PenWidth = 1;

            myPane.YAxis.MinorGrid.IsVisible = true;
            myPane.YAxis.MinorGrid.Color = gridcolor;
            myPane.YAxis.MinorGrid.DashOff = 1;
            myPane.YAxis.MinorGrid.DashOn = 5;
            myPane.YAxis.MinorGrid.PenWidth = 1;

            //to control the step unit
            myPane.YAxis.Scale.MajorStep = 2;
            //myPane.Chart.Fill.IsVisible = false;
            myPane.XAxis.Scale.Max = 11;
            zgc.GraphPane.CurveList.Clear();
            // Make up some data points from the Sine function
            for (int i = 0; i < linecount; i++)
            {
                PointPairList list = new PointPairList();
                Random innerRnd = new Random();
                double tmp; tmp = 0;
                double y; y = 0;
                for (double x = 0; x < 12; x++)
                {
                    //this is the generated graph function
                    switch (i)
                    {
                        case 0:
                            tmp = (innerRnd.Next() % 20.0) - 10.0;
                            y = (3 / (1 + Math.Exp((-x + 6) / 2)) - 1.5) + (tmp / (20 + 3 * Math.Abs(x - 30)));
                            break;
                        case 1:
                            tmp = (innerRnd.Next() % 20.0) - 10.0;
                            y = Math.Sin((x) / 4.0) * (1 + tmp / 20);
                            break;
                        default:
                            tmp = (innerRnd.Next() % 20.0) - 10.0;
                            y = Math.Sin(x * tmp * Math.PI / 15.0);
                            break;
                    }
                    //Trace.WriteLine(tmp.ToString());
                    list.Add(x, y);
                }

                // Generate a blue curve with circle symbols, and "My Curve 2" in the legend
                LineItem myCurve = myPane.AddCurve("", list, (linecolor == Color.Empty) ? LogMsgTypeColor[i] : linecolor,
                    (linecolor == Color.Empty) ? SymbolType.Circle : SymbolType.None);
                myCurve.Line.IsSmooth = true;
                // Fill the area under the curve with a white-red gradient at 45 degrees
                //myCurve.Line.Fill = new Fill(Color.White, Color.Red, 45F);
                // Make the symbols opaque by filling them with white
                myCurve.Symbol.Fill = new Fill((linecolor == Color.Empty) ? LogMsgTypeColor[i] : linecolor);

                // Fill the axis background with a color gradient
                myPane.Chart.Fill = new Fill(backgroundcolor, backgroundcolor, 45F);

                // Fill the pane background with a color gradient
                myPane.Fill = new Fill(Color.LightGray, Color.LightGray, 45F);

                // Calculate the Axis Scale Ranges

            }
            zgc.AxisChange();
            //zgc.Invalidate();
        }


        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
            }

            else if (!(e.Error == null))
            {
            }

            else
            {
            }
        }
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
        }

        private void pictureBox4_Click(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void frmTerminal_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            flag_idv_test = true;
            trdTestHeadset = new Thread(new ThreadStart(this.test_headset));
            trdTestHeadset.IsBackground = true;
            trdTestHeadset.Start();
            disable_excl_btns();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            flag_idv_test = true;
            trdTestInfrared = new Thread(new ThreadStart(this.test_infrared));
            trdTestInfrared.IsBackground = true;
            trdTestInfrared.Start();
            disable_excl_btns();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            flag_idv_test = true;
            trdTestLED = new Thread(new ThreadStart(this.test_led));
            trdTestLED.IsBackground = true;
            trdTestLED.Start();
            disable_excl_btns();
        }

    }
}